import storage from '@/utils/storage.js'
import { TOKEN, USERINFO } from '@/store/constant.js'
import userApi from '@/api/user.js'

const state = {
  // token
  token: storage.get(TOKEN, ''),
  // 用户信息
  userInfo: storage.get(USERINFO, {})
}

const mutations = {
  // token与userInfo一起，根据项目具体情况看是否需要拆分分享存token、userInfo
  setUser: (state, options) => {
    state.token = options.token
    storage.set(TOKEN, options.token)
    state.userInfo = options
    storage.set(USERINFO, options)
  },
}

const actions = {
  // 可以在这里调用接口
  login: async ({ commit }, data) => {
    const res = await userApi.login(data)
    res && commit('setUser', res)
    return res
  }
}

const getters = {
  token: (state) => state.token,
  userInfo: (state) => state.userInfo,
}

export default {
  state,
  mutations,
  actions,
  getters
}